package ca.kooki.codesnippet;

import java.util.Date;

import ca.kooki.codesnippet.core.Identifier;
import ca.kooki.codesnippet.core.SearchInput;
import ca.kooki.codesnippet.core.SystemDate;
import ca.kooki.codesnippet.core.User;

public class Tag {

  //```````````````````````
  // MEMBER VARIABLES
  //```````````````````````
  
  private Description _description;
  private CodeSnippet _snippet;
  private User _user;
  private Date _updated;
 
  private Identifier _id;
  
  //```````````````````````
  // CONSTRUCTOR
  //```````````````````````

  public Tag(String title, String keywords, CodeSnippet snippet, String name)
  {
    init(title,keywords,snippet,new User(name));
  }
  
  public Tag(String title, String keywords, CodeSnippet snippet, User user)
  {
    init(title,keywords,snippet,user);
  }

  private void init(String title, String keywords, CodeSnippet snippet, User user)
  {
    _description = new Description(title,keywords);
    _snippet = snippet;
    _user = user;
    _updated = SystemDate.Now();
    _id = new Identifier(this.getClass());
  }
 
  
  //```````````````````````
  // INTERFACE
  //```````````````````````
  
  public boolean isOfficial()
  {
    return _id.isOfficial();
  }
  
  public String getId()
  {
    return _id.getId();
  }
  
  public  void setId(String newId)
  {
    _id.setId(newId);
  }
  
  public String getTitle() 
  {
    return _description.getTitle();
  }

  public String getKeywords() 
  {
    return _description.getKeywords();
  }

  public User getUser() 
  {
    return _user;
  }
  
  public String[] getKeywordList()
  {
    return _description.getKeywordList();
  }
  
  public CodeSnippet getCodeSnippet()
  {
    return _snippet;
  }
  
  public Date getUpdated()
  {
    return _updated;
  }
  
  public void setUpdated(Date updated)
  {
    _updated = updated;
  }
  
  public boolean isRelevant(SearchInput search)
  {
    if (search.isAll())
    {
      return true;
    }
    else
    {
      boolean hasKeywords = search.isRelevantTo(_description.getKeywords());
      boolean hasUsername = !search.hasUsername() || search.getUsername().equals(getUser().getName());
      return hasKeywords && hasUsername;
    }
  }
  
  public boolean isRelevant(String input)
  {
    return isRelevant(new SearchInput(input));
  }
  
  public String toString()
  {
    return String.format("%s[%s];%s", _description.toString(),_snippet.toString(),_user);
  }
  
  public boolean equals(Object obj)
  {
    if (obj == null || !obj.getClass().equals(Tag.class))
    {
      return false;
    }

    Tag compareTo = (Tag)obj;
    
    if (compareTo.isOfficial() && isOfficial())
    {
      return compareTo.getId().equals(getId());
    }
    else
    {
      return this.toString().equals(compareTo.toString());
    }
  }
  
}
